4 * (X)HTML sanitizer for MediaWiki
6 * Copyright (C) 2002-2005 Brion Vibber <brion@pobox.com> et al
7 * http://www.mediawiki.org/
9 * This program is free software; you can redistribute it and/or modify
10 * it under the terms of the GNU General Public License as published by
11 * the Free Software Foundation; either version 2 of the License, or
12 * (at your option) any later version.
14 * This program is distributed in the hope that it will be useful,
15 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 * GNU General Public License for more details.
19 * You should have received a copy of the GNU General Public License along
20 * with this program; if not, write to the Free Software Foundation, Inc.,
21 * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
22 * http://www.gnu.org/copyleft/gpl.html
29 * Regular expression to match various types of character references in
30 * Sanitizer::normalizeCharReferences and Sanitizer::decodeCharReferences
32 define( 'MW_CHAR_REFS_REGEX',
40 * Regular expression to match HTML/XML attribute pairs within a tag.
41 * Allows some... latitude.
42 * Used in Sanitizer::fixTagAttributes and Sanitizer::decodeTagAttributes
44 $attrib = '[A-Za-z0-9]';
45 $space = '[\x09\x0a\x0d\x20]';
46 define( 'MW_ATTRIBS_REGEX',
47 "/(?:^|$space)($attrib+)
50 # The attribute value: quoted or alone
53 | ([a-zA-Z0-9!#$%&()*,\\-.\\/:;<>?@[\\]^_`{|}~]+)
54 | (\#[0-9a-fA-F]+) # Technically wrong, but lots of
55 # colors are specified like this.
56 # We'll be normalizing it.
58 )?(?=$space|\$)/sx" );
61 * List of all named character entities defined in HTML 4.01
62 * http://www.w3.org/TR/html4/sgml/entities.html
65 global $wgHtmlEntities;
66 $wgHtmlEntities = array(
322 * Cleans up HTML, removes dangerous tags and attributes, and
323 * removes HTML comments
325 * @param string $text
326 * @param callback $processCallback to do any variable or parameter replacements in HTML attribute values
327 * @param array $args for the processing callback
330 function removeHTMLtags( $text, $processCallback = null, $args = array() ) {
331 global $wgUseTidy, $wgUserHtml;
332 $fname = 'Parser::removeHTMLtags';
333 wfProfileIn( $fname );
336 $htmlpairs = array( # Tags that must be closed
337 'b', 'del', 'i', 'ins', 'u', 'font', 'big', 'small', 'sub', 'sup', 'h1',
338 'h2', 'h3', 'h4', 'h5', 'h6', 'cite', 'code', 'em', 's',
339 'strike', 'strong', 'tt', 'var', 'div', 'center',
340 'blockquote', 'ol', 'ul', 'dl', 'table', 'caption', 'pre',
341 'ruby', 'rt' , 'rb' , 'rp', 'p', 'span'
344 'br', 'hr', 'li', 'dt', 'dd'
346 $htmlnest = array( # Tags that can be nested--??
347 'table', 'tr', 'td', 'th', 'div', 'blockquote', 'ol', 'ul',
348 'dl', 'font', 'big', 'small', 'sub', 'sup', 'span'
350 $tabletags = array( # Can only appear inside table
354 $htmlpairs = array();
355 $htmlsingle = array();
357 $tabletags = array();
360 $htmlsingle = array_merge( $tabletags, $htmlsingle );
361 $htmlelements = array_merge( $htmlsingle, $htmlpairs );
363 # Remove HTML comments
364 $text = Sanitizer
::removeHTMLcomments( $text );
366 $bits = explode( '<', $text );
367 $text = array_shift( $bits );
369 $tagstack = array(); $tablestack = array();
370 foreach ( $bits as $x ) {
371 $prev = error_reporting( E_ALL
& ~
( E_NOTICE | E_WARNING
) );
372 preg_match( '/^(\\/?)(\\w+)([^>]*)(\\/{0,1}>)([^<]*)$/',
374 list( $qbar, $slash, $t, $params, $brace, $rest ) = $regs;
375 error_reporting( $prev );
378 if ( in_array( $t = strtolower( $t ), $htmlelements ) ) {
382 if ( ! in_array( $t, $htmlsingle ) &&
383 ( $ot = @array_pop
( $tagstack ) ) != $t ) {
384 @array_push
( $tagstack, $ot );
387 if ( $t == 'table' ) {
388 $tagstack = array_pop( $tablestack );
393 # Keep track for later
394 if ( in_array( $t, $tabletags ) &&
395 ! in_array( 'table', $tagstack ) ) {
397 } else if ( in_array( $t, $tagstack ) &&
398 ! in_array ( $t , $htmlnest ) ) {
400 } else if ( ! in_array( $t, $htmlsingle ) ) {
401 if ( $t == 'table' ) {
402 array_push( $tablestack, $tagstack );
405 array_push( $tagstack, $t );
408 # Replace any variables or template parameters with
410 if( is_callable( $processCallback ) ) {
411 call_user_func_array( $processCallback, array( &$params, $args ) );
414 # Strip non-approved attributes from the tag
415 $newparams = Sanitizer
::fixTagAttributes( $params, $t );
418 $rest = str_replace( '>', '>', $rest );
419 $text .= "<$slash$t$newparams$brace$rest";
423 $text .= '<' . str_replace( '>', '>', $x);
425 # Close off any remaining tags
426 while ( is_array( $tagstack ) && ($t = array_pop( $tagstack )) ) {
428 if ( $t == 'table' ) { $tagstack = array_pop( $tablestack ); }
431 # this might be possible using tidy itself
432 foreach ( $bits as $x ) {
433 preg_match( '/^(\\/?)(\\w+)([^>]*)(\\/{0,1}>)([^<]*)$/',
435 @list
( $qbar, $slash, $t, $params, $brace, $rest ) = $regs;
436 if ( in_array( $t = strtolower( $t ), $htmlelements ) ) {
437 if( is_callable( $processCallback ) ) {
438 call_user_func_array( $processCallback, array( &$params, $args ) );
440 $newparams = Sanitizer
::fixTagAttributes( $params, $t );
441 $rest = str_replace( '>', '>', $rest );
442 $text .= "<$slash$t$newparams$brace$rest";
444 $text .= '<' . str_replace( '>', '>', $x);
448 wfProfileOut( $fname );
453 * Remove '<!--', '-->', and everything between.
454 * To avoid leaving blank lines, when a comment is both preceded
455 * and followed by a newline (ignoring spaces), trim leading and
456 * trailing spaces and one of the newlines.
459 * @param string $text
462 function removeHTMLcomments( $text ) {
463 $fname='Parser::removeHTMLcomments';
464 wfProfileIn( $fname );
465 while (($start = strpos($text, '<!--')) !== false) {
466 $end = strpos($text, '-->', $start +
4);
467 if ($end === false) {
468 # Unterminated comment; bail out
474 # Trim space and newline if the comment is both
475 # preceded and followed by a newline
476 $spaceStart = max($start - 1, 0);
477 $spaceLen = $end - $spaceStart;
478 while (substr($text, $spaceStart, 1) === ' ' && $spaceStart > 0) {
482 while (substr($text, $spaceStart +
$spaceLen, 1) === ' ')
484 if (substr($text, $spaceStart, 1) === "\n" and substr($text, $spaceStart +
$spaceLen, 1) === "\n") {
485 # Remove the comment, leading and trailing
486 # spaces, and leave only one newline.
487 $text = substr_replace($text, "\n", $spaceStart, $spaceLen +
1);
490 # Remove just the comment.
491 $text = substr_replace($text, '', $start, $end - $start);
494 wfProfileOut( $fname );
499 * Take a tag soup fragment listing an HTML element's attributes
500 * and normalize it to well-formed XML, discarding unwanted attributes.
502 * - Normalizes attribute names to lowercase
503 * - Discards attributes not on a whitelist for the given element
504 * - Turns broken or invalid entities into plaintext
505 * - Double-quotes all attribute values
506 * - Attributes without values are given the name as attribute
507 * - Double attributes are discarded
508 * - Unsafe style attributes are discarded
509 * - Prepends space if there are attributes.
511 * @param string $text
512 * @param string $element
515 * @todo Check for legal values where the DTD limits things.
516 * @todo Check for unique id attribute :P
518 function fixTagAttributes( $text, $element ) {
519 if( trim( $text ) == '' ) {
524 # Since we quote this later, this can be anything distinguishable
525 # from the end of the attribute
534 $whitelist = array_flip( Sanitizer
::attributeWhitelist( $element ) );
536 foreach( $pairs as $set ) {
537 $attribute = strtolower( $set[1] );
538 if( !isset( $whitelist[$attribute] ) ) {
542 $raw = Sanitizer
::getTagAttributeCallback( $set );
543 $value = Sanitizer
::normalizeAttributeValue( $raw );
545 # Strip javascript "expression" from stylesheets.
546 # http://msdn.microsoft.com/workshop/author/dhtml/overview/recalc.asp
547 if( $attribute == 'style' && preg_match(
548 '/(expression|tps*:\/\/|url\\s*\().*/is',
549 Sanitizer
::decodeCharReferences( $value ) ) ) {
554 # Templates and links may be expanded in later parsing,
555 # creating invalid or dangerous output. Suppress this.
556 $value = strtr( $value, array(
559 "''" => '''',
560 'ISBN' => 'ISBN',
562 'PMID' => 'PMID',
564 $value = preg_replace(
565 '/(' . URL_PROTOCOLS
. '):/',
566 '\\1:', $value );
568 if( !isset( $attribs[$attribute] ) ) {
569 $attribs[$attribute] = "$attribute=\"$value\"";
572 if( empty( $attribs ) ) {
575 return ' ' . implode( ' ', $attribs );
580 * Return an associative array of attribute names and values from
581 * a partial tag string. Attribute names are forces to lowercase,
582 * character references are decoded to UTF-8 text.
587 function decodeTagAttributes( $text ) {
590 if( trim( $text ) == '' ) {
602 foreach( $pairs as $set ) {
603 $attribute = strtolower( $set[1] );
604 $value = Sanitizer
::getTagAttributeCallback( $set );
605 $attribs[$attribute] = Sanitizer
::decodeCharReferences( $value );
611 * Pick the appropriate attribute value from a match set from the
612 * MW_ATTRIBS_REGEX matches.
618 function getTagAttributeCallback( $set ) {
619 if( isset( $set[6] ) ) {
620 # Illegal #XXXXXX color with no quotes.
622 } elseif( isset( $set[5] ) ) {
625 } elseif( isset( $set[4] ) ) {
628 } elseif( isset( $set[3] ) ) {
631 } elseif( !isset( $set[2] ) ) {
632 # In XHTML, attributes must have a value.
633 # For 'reduced' form, return explicitly the attribute name here.
636 wfDebugDieBacktrace( "Tag conditions not met. This should never happen and is a bug." );
641 * Normalize whitespace and character references in an XML source-
642 * encoded text for an attribute value.
644 * See http://www.w3.org/TR/REC-xml/#AVNormalize for background,
645 * but note that we're not returning the value, but are returning
646 * XML source fragments that will be slapped into output.
648 * @param string $text
652 function normalizeAttributeValue( $text ) {
653 return str_replace( '"', '"',
655 '/\r\n|[\x20\x0d\x0a\x09]/',
657 Sanitizer
::normalizeCharReferences( $text ) ) );
661 * Ensure that any entities and character references are legal
662 * for XML and XHTML specifically. Any stray bits will be
663 * &-escaped to result in a valid text fragment.
665 * a. any named char refs must be known in XHTML
666 * b. any numeric char refs must be legal chars, not invalid or forbidden
667 * c. use &#x, not &#X
668 * d. fix or reject non-valid attributes
670 * @param string $text
674 function normalizeCharReferences( $text ) {
675 return preg_replace_callback(
677 array( 'Sanitizer', 'normalizeCharReferencesCallback' ),
681 * @param string $matches
684 function normalizeCharReferencesCallback( $matches ) {
686 if( $matches[1] != '' ) {
687 $ret = Sanitizer
::normalizeEntity( $matches[1] );
688 } elseif( $matches[2] != '' ) {
689 $ret = Sanitizer
::decCharReference( $matches[2] );
690 } elseif( $matches[3] != '' ) {
691 $ret = Sanitizer
::hexCharReference( $matches[3] );
692 } elseif( $matches[4] != '' ) {
693 $ret = Sanitizer
::hexCharReference( $matches[4] );
695 if( is_null( $ret ) ) {
696 return htmlspecialchars( $matches[0] );
703 * If the named entity is defined in the HTML 4.0/XHTML 1.0 DTD,
704 * return the named entity reference as is. Otherwise, returns
705 * HTML-escaped text of pseudo-entity source (eg &foo;)
707 * @param string $name
710 function normalizeEntity( $name ) {
711 global $wgHtmlEntities;
712 if( isset( $wgHtmlEntities[$name] ) ) {
715 return "&$name;";
719 function decCharReference( $codepoint ) {
720 $point = IntVal( $codepoint );
721 if( Sanitizer
::validateCodepoint( $point ) ) {
722 return sprintf( '&#%d;', $point );
728 function hexCharReference( $codepoint ) {
729 $point = hexdec( $codepoint );
730 if( Sanitizer
::validateCodepoint( $point ) ) {
731 return sprintf( '&#x%x;', $point );
738 * Returns true if a given Unicode codepoint is a valid character in XML.
739 * @param int $codepoint
742 function validateCodepoint( $codepoint ) {
743 return ($codepoint == 0x09)
744 ||
($codepoint == 0x0a)
745 ||
($codepoint == 0x0d)
746 ||
($codepoint >= 0x20 && $codepoint <= 0xd7ff)
747 ||
($codepoint >= 0xe000 && $codepoint <= 0xfffd)
748 ||
($codepoint >= 0x10000 && $codepoint <= 0x10ffff);
752 * Decode any character references, numeric or named entities,
753 * in the text and return a UTF-8 string.
755 * @param string $text
759 function decodeCharReferences( $text ) {
760 return preg_replace_callback(
762 array( 'Sanitizer', 'decodeCharReferencesCallback' ),
767 * @param string $matches
770 function decodeCharReferencesCallback( $matches ) {
771 if( $matches[1] != '' ) {
772 return Sanitizer
::decodeEntity( $matches[1] );
773 } elseif( $matches[2] != '' ) {
774 return Sanitizer
::decodeChar( intval( $matches[2] ) );
775 } elseif( $matches[3] != '' ) {
776 return Sanitizer
::decodeChar( hexdec( $matches[3] ) );
777 } elseif( $matches[4] != '' ) {
778 return Sanitizer
::decodeChar( hexdec( $matches[4] ) );
780 # Last case should be an ampersand by itself
785 * Return UTF-8 string for a codepoint if that is a valid
786 * character reference, otherwise U+FFFD REPLACEMENT CHARACTER.
787 * @param int $codepoint
791 function decodeChar( $codepoint ) {
792 if( Sanitizer
::validateCodepoint( $codepoint ) ) {
793 return codepointToUtf8( $codepoint );
795 return UTF8_REPLACEMENT
;
800 * If the named entity is defined in the HTML 4.0/XHTML 1.0 DTD,
801 * return the UTF-8 encoding of that character. Otherwise, returns
802 * pseudo-entity source (eg &foo;)
804 * @param string $name
807 function decodeEntity( $name ) {
808 global $wgHtmlEntities;
809 if( isset( $wgHtmlEntities[$name] ) ) {
810 return codepointToUtf8( $wgHtmlEntities[$name] );
817 * Fetch the whitelist of acceptable attributes for a given
820 * @param string $element
823 function attributeWhitelist( $element ) {
825 if( !isset( $list ) ) {
826 $list = Sanitizer
::setupAttributeWhitelist();
828 return isset( $list[$element] )
836 function setupAttributeWhitelist() {
837 $common = array( 'id', 'class', 'lang', 'dir', 'title', 'style' );
838 $block = array_merge( $common, array( 'align' ) );
839 $tablealign = array( 'align', 'char', 'charoff', 'valign' );
840 $tablecell = array( 'abbr',
846 'nowrap', # deprecated
847 'width', # deprecated
848 'height', # deprecated
849 'bgcolor' # deprecated
852 # Numbers refer to sections in HTML 4.01 standard describing the element.
853 # See: http://www.w3.org/TR/html4/
857 'center' => $common, # deprecated
858 'span' => $block, # ??
887 'blockquote' => array_merge( $common, array( 'cite' ) ),
898 'br' => array( 'id', 'class', 'title', 'style', 'clear' ),
901 'pre' => array_merge( $common, array( 'width' ) ),
904 'ins' => array_merge( $common, array( 'cite', 'datetime' ) ),
905 'del' => array_merge( $common, array( 'cite', 'datetime' ) ),
908 'ul' => array_merge( $common, array( 'type' ) ),
909 'ol' => array_merge( $common, array( 'type', 'start' ) ),
910 'li' => array_merge( $common, array( 'type', 'value' ) ),
918 'table' => array_merge( $common,
919 array( 'summary', 'width', 'border', 'frame',
920 'rules', 'cellspacing', 'cellpadding',
921 'align', 'bgcolor', 'frame', 'rules',
925 'caption' => array_merge( $common, array( 'align' ) ),
928 'thead' => array_merge( $common, $tablealign ),
929 'tfoot' => array_merge( $common, $tablealign ),
930 'tbody' => array_merge( $common, $tablealign ),
933 'colgroup' => array_merge( $common, array( 'span', 'width' ), $tablealign ),
934 'col' => array_merge( $common, array( 'span', 'width' ), $tablealign ),
937 'tr' => array_merge( $common, array( 'bgcolor' ), $tablealign ),
940 'td' => array_merge( $common, $tablecell, $tablealign ),
941 'th' => array_merge( $common, $tablecell, $tablealign ),
954 'font' => array_merge( $common, array( 'size', 'color', 'face' ) ),
958 'hr' => array_merge( $common, array( 'noshade', 'size', 'width' ) ),
960 # XHTML Ruby annotation text module, simple ruby only.
961 # http://www.w3c.org/TR/ruby/
966 'rt' => $common, #array_merge( $common, array( 'rbspan' ) ),
973 * Take a fragment of (potentially invalid) HTML and return
974 * a version with any tags removed, encoded suitably for literal
975 * inclusion in an attribute value.
977 * @param string $text HTML fragment
980 function stripAllTags( $text ) {
982 $text = preg_replace( '/<[^>]*>/', '', $text );
984 # Normalize &entities and whitespace
985 $text = Sanitizer
::normalizeAttributeValue( $text );
987 # Will be placed into "double-quoted" attributes,
988 # make sure remaining bits are safe.
990 array('<', '>', '"'),
991 array('<', '>', '"'),